package com.butterfly.hotkey.core.enums;

import cn.hutool.core.util.StrUtil;

/**
 * 缓存时效的时间，借鉴RocketMq的延时
 * ！！！ 谨慎添加枚举，本地缓存的MAP粒度使用该枚举
 *
 * @author butterfly
 */
public enum CacheDurationEnum {

    /**
     * 缓存时间，s-秒 m-分 h-时 d-天
     */
    DURATION_10S("10s", 10),
    DURATION_30S("30s", 30),
    DURATION_1M("1m", 60),
    DURATION_2M("2m", 120),
    DURATION_3M("3m", 180),
    DURATION_4M("4m", 240),
    DURATION_5M("5m", 300),
    DURATION_10M("10m", 600),
    DURATION_30M("30m", 30 * 60),
    /**
     * ！！！避免使用长本地缓存
     */
    DURATION_1H("1h", 3600);


    /**
     * 缓存级别
     */
    private final String duration;

    /**
     * 对应的缓存秒数
     */
    private final Integer seconds;

    CacheDurationEnum(String duration, Integer seconds) {
        this.duration = duration;
        this.seconds = seconds;
    }

    public String getDuration() {
        return duration;
    }

    public Integer getSeconds() {
        return seconds;
    }

    public static CacheDurationEnum getByDuration(String duration) {
        if (StrUtil.isBlank(duration)) {
            return null;
        }
        for (CacheDurationEnum item : CacheDurationEnum.values()) {
            if (item.getDuration().equals(duration)) {
                return item;
            }
        }
        return null;
    }

    /**
     * 获取缓存间隔，默认5s，最大2H
     *
     * @param duration 缓存间隔
     * @return 缓存的秒数
     */
    public static int getSeconds(String duration) {
        CacheDurationEnum cacheDurationEnum = getByDuration(duration);
        // 最低5s
        if (cacheDurationEnum == null) {
            return CacheDurationEnum.DURATION_10S.getSeconds();
        }
        return cacheDurationEnum.getSeconds();
    }


}
